import Vue from 'vue'
import Router from 'vue-router'
import LoginPage from '@/pages/LoginPage'
import ContractList from '@/pages/ContractList'
import ShoppingList from '@/pages/ShoppingList'
import HistoryList from '@/pages/HistoryList'
import Tabbar from '@/pages/Tabbar'

import storage from '../store/storage'


Vue.use(Router)

const router = new Router({
  routes: [
    {
      path: '/',
      redirect: '/login'
    },
    {
      path: '/login',
      name: 'Login',
      component: LoginPage,
      meta: {
        title: '登录系统'
      }
    },
    {
      path: '/shopping-list',
      name: 'ShoppingList',
      component: ShoppingList,
      meta: {
        title: '购物车',
        hasAuth: true
      },
    },
    {
      path: '/tabbar',
      name: 'Tabbar',
      component: Tabbar,
      children: [{
        path: '/contract-list',
        name: 'ContractList',
        component: ContractList,
        meta: {
          title: '合同列表',
          hasAuth: true
        },
      }, {
        path: '/history-list',
        name: 'HistoryList',
        component: HistoryList,
        meta: {
          title: '历史订单',
          hasAuth: true
        },
      }]
    },
  ]
})

router.afterEach(route => {
  if (route.meta && route.meta.title) {
    document.title = route.meta.title;
  } else {
    document.title = '订单系统';
  }
})

router.beforeEach((to, from, next) => {
  console.log('to=========', to);
  console.log('from===========', from);

  if (to.meta && to.meta.hasAuth) {
    if (!storage.get('token')) {
      if (from.path === '/' || from.path === '/login') {
        next(false);
        return;
      }
      router.push({ path: '/login' });
    }
  }
  next();
})

export default router;